<?php

namespace common\components;

use Yii;
use yii\base\Component;
use common\helpers\ArrayHelper;
use common\helpers\UrlHelper;

class JDService extends Component
{

    private $appKey = 'YourKey';    //  你的Key
    private $appScret = 'YourSecret';   //  你的Secret
    private $app_token_json = '{}'; //  第一次需要手动授权获取京东Token然后粘贴到这里



    //  刷新accessToken
    private function refreshAccessToken(){
        $filePath = dirname(dirname(__FILE__)).'/Config/KelperToken.config';     //  Token文本保存路径
        if (file_exists($filePath)){
            $handle = fopen($filePath,'r');
            $tokenJson = fread($handle,8142);
        }else{
            //  插入默认的token
            fwrite(fopen($filePath,'w'),$this->app_token_json);
            $tokenJson = $this->app_token_json;
        }
        if (substr($tokenJson, 0,3) == pack('CCC',0xef,0xbb,0xbf)) {
            $tokenJson = substr($tokenJson, 3);
        }
        $res = json_decode(trim($tokenJson),true);   //  解析不了可能是文本出了问题，注意BOM头
        //  判断
        if ($res['code'] == 0){
            if ($res['expires_in']*1000 + $res['time']  <  self::getMillisecond() - 86400000){    //  access_token失效前一天
                //  获取刷新token的url
                $refreshUrl = "https://kploauth.jd.com/oauth/token?grant_type=oauth_refresh_token";//&app_key=yourappkey&app_secret=yourappsecret&refresh_token=xxxxxxxx
                $refreshUrl .= '&app_key='.$this->appKey;
                $refreshUrl .= '&app_secret='.$this->appScret;
                $refreshUrl .= '&refresh_token='.$res['refresh_token'];
                //  获取新的token数据
                $newAccessTokenJson = self::curl_get($refreshUrl);
                //  写入文本
                fwrite(fopen($filePath,'w'),$newAccessTokenJson);
                //  解析成数组
                $newAccessTokenArr = json_decode($newAccessTokenJson,true);
                $accessToken = $newAccessTokenArr['access_token'];
            }else{
                $accessToken = $res['access_token'];
            }
            return $accessToken;
        }else{
            //  如果refresh_token过期，将会返回错误码code:2011;msg:refresh_token过期
            return $res['msg'];
        }
    }

    //  get请求
    private static function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;

    }

    //  post请求

    private static function curl_post($url,$curlPost){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    //  获取13位时间戳
    private static function  getMillisecond(){
        list($t1, $t2) = explode(' ', microtime());
        return sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

}